import { _decorator, Component, Label, Node, ProgressBar, Color, Sprite, tween, director } from 'cc';
import { GameManager } from '../core/GameManager';

const { ccclass, property } = _decorator;

/**
 * 倒计时状态枚举
 */
enum TimerState {
    IDLE,    // 闲置
    RUNNING, // 运行中
    PAUSED,  // 暂停
    FINISHED // 结束
}

/**
 * 计时器组件
 * 负责游戏倒计时功能
 */
@ccclass('Timer')
export class Timer extends Component {
    @property(Label)
    private timerLabel: Label = null;
    
    @property(ProgressBar)
    private timerBar: ProgressBar = null;
    
    @property(Sprite)
    private timerBarSprite: Sprite = null;
    
    @property({type: Color})
    private normalColor: Color = new Color(0, 255, 0, 255);
    
    @property({type: Color})
    private warningColor: Color = new Color(255, 255, 0, 255);
    
    @property({type: Color})
    private dangerColor: Color = new Color(255, 0, 0, 255);
    
    @property({type: Number, tooltip: "警告时间阈值（秒）"})
    private warningThreshold: number = 30;
    
    @property({type: Number, tooltip: "危险时间阈值（秒）"})
    private dangerThreshold: number = 10;
    
    @property({type: Boolean, tooltip: "是否自动启动"})
    private autoStart: boolean = false;
    
    private _maxTime: number = 60; // 最大时间（秒）
    private _remainingTime: number = 0; // 剩余时间（秒）
    private _timerState: TimerState = TimerState.IDLE;
    private _tickCallback = null;
    
    // 生命周期函数
    onLoad() {
        if (!this.timerLabel) {
            this.timerLabel = this.getComponent(Label);
        }
        
        // 获取游戏管理器中的最大时间
        const gameManagerNode = director.getScene().getChildByName('GameManager');
        if (gameManagerNode) {
            const gameManager = gameManagerNode.getComponent(GameManager);
            if (gameManager) {
                this._maxTime = gameManager.maxTime;
            }
        }
        
        this._remainingTime = this._maxTime;
    }
    
    start() {
        // 初始化显示
        this.updateTimerDisplay();
        
        // 如果设置了自动启动，则开始计时
        if (this.autoStart) {
            this.startTimer();
        }
    }
    
    onDestroy() {
        // 确保定时器被清除
        this.stopTimer();
    }
    
    /**
     * 开始计时器
     */
    public startTimer(): void {
        console.log("开始计时器");
        // 先停止现有的计时器，防止多个计时器同时运行
        this.stopTimer();
        
        this._timerState = TimerState.RUNNING;
        
        // 确保时间正确
        if (this._remainingTime <= 0) {
            this._remainingTime = this._maxTime;
        }
        
        this.updateTimerDisplay();
        
        // 创建计时回调
        this._tickCallback = () => {
            this._remainingTime -= 1;
            
            if (this._remainingTime <= 0) {
                this._remainingTime = 0;
                this.timeUp();
            }
            
            this.updateTimerDisplay();
        };
        
        // 每秒执行一次
        this.schedule(this._tickCallback, 1);
        console.log("计时器已启动，剩余时间: " + this._remainingTime + "秒");
    }
    
    /**
     * 暂停计时器
     */
    public pauseTimer(): void {
        if (this._timerState === TimerState.RUNNING) {
            this._timerState = TimerState.PAUSED;
            this.unschedule(this._tickCallback);
        }
    }
    
    /**
     * 恢复计时器
     */
    public resumeTimer(): void {
        if (this._timerState === TimerState.PAUSED) {
            this._timerState = TimerState.RUNNING;
            this.schedule(this._tickCallback, 1);
        }
    }
    
    /**
     * 停止计时器
     */
    public stopTimer(): void {
        this._timerState = TimerState.IDLE;
        this.unschedule(this._tickCallback);
    }
    
    /**
     * 重置计时器
     */
    public resetTimer(): void {
        console.log("重置计时器");
        this.stopTimer();
        
        // 获取最新的最大时间值
        const gameManagerNode = director.getScene().getChildByName('GameManager');
        if (gameManagerNode) {
            const gameManager = gameManagerNode.getComponent(GameManager);
            if (gameManager) {
                this._maxTime = gameManager.maxTime;
            }
        }
        
        this._remainingTime = this._maxTime;
        this._timerState = TimerState.IDLE;
        this.updateTimerDisplay();
        console.log("计时器已重置，最大时间: " + this._maxTime + "秒");
    }
    
    /**
     * 更新计时器显示
     */
    private updateTimerDisplay(): void {
        // 更新文本显示
        if (this.timerLabel) {
            const minutes = Math.floor(this._remainingTime / 60);
            const seconds = this._remainingTime % 60;
            
            // 使用兼容的方式格式化时间字符串
            const minutesStr = minutes < 10 ? '0' + minutes : minutes.toString();
            const secondsStr = seconds < 10 ? '0' + seconds : seconds.toString();
            
            this.timerLabel.string = `${minutesStr}:${secondsStr}`;
        }
        
        // 更新进度条
        if (this.timerBar) {
            const progress = this._remainingTime / this._maxTime;
            this.timerBar.progress = progress;
            
            // 根据剩余时间更新颜色
            this.updateTimerColor();
            
            // 当时间不多时添加闪烁效果
            if (this._remainingTime <= this.dangerThreshold) {
                this.applyBlinkEffect();
            }
        }
    }
    
    /**
     * 更新计时器颜色
     */
    private updateTimerColor(): void {
        if (!this.timerBarSprite) return;
        
        if (this._remainingTime <= this.dangerThreshold) {
            this.timerBarSprite.color = this.dangerColor;
        } else if (this._remainingTime <= this.warningThreshold) {
            this.timerBarSprite.color = this.warningColor;
        } else {
            this.timerBarSprite.color = this.normalColor;
        }
    }
    
    /**
     * 应用闪烁效果
     */
    private applyBlinkEffect(): void {
        if (!this.timerBarSprite || !this.timerBarSprite.node) return;
        
        // 创建一个简单的闪烁动画
        tween(this.timerBarSprite)
            .to(0.3, { color: new Color(255, 255, 255, 255) })
            .to(0.3, { color: this.dangerColor })
            .union()
            .repeat(1)
            .start();
    }
    
    /**
     * 时间到
     */
    private timeUp(): void {
        this._timerState = TimerState.FINISHED;
        this.unschedule(this._tickCallback);
        
        // 通知游戏管理器时间到
        const gameManagerNode = director.getScene().getChildByName('GameManager');
        if (gameManagerNode) {
            const gameManager = gameManagerNode.getComponent(GameManager);
            if (gameManager) {
                gameManager.endGame();
            }
        }
    }
    
    /**
     * 添加额外时间
     */
    public addTime(seconds: number): void {
        if (this._timerState !== TimerState.RUNNING) return;
        
        this._remainingTime += seconds;
        if (this._remainingTime > this._maxTime) {
            this._remainingTime = this._maxTime;
        }
        
        this.updateTimerDisplay();
    }
    
    /**
     * 获取剩余时间
     */
    public get remainingTime(): number {
        return this._remainingTime;
    }
    
    /**
     * 获取计时器状态
     */
    public get timerState(): TimerState {
        return this._timerState;
    }
} 